package com.yanq.liancar.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialog;
import com.vondear.rxui.view.dialog.RxDialogEditSureCancel;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.BOrderListAdapter;
import com.yanq.liancar.adapter.ShopOrderListAdapter;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.OrderListBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;
import com.yanq.liancar.view.SimplePadding20Decoration;
import com.yanq.liancar.view.SimplePaddingDecoration;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SmallBOrderListActivity extends BaseToolbarActivity {
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_delete)
    TextView tv_delete;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<String> titles;
    private String where;
    private int page = 1;
    private Boolean isClear = true;
    private BOrderListAdapter adapter;
    private List<OrderListBean.DataBean.OrderBean> mList = new ArrayList<>();
    private int status,checked;
    private boolean isDelete=true;
    private List<String> mIdList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small_b_orderlist);
        Utils.setStatusBar(this, true, false);
        where = getIntent().getExtras().getString("where");

        mTvTitle.setText("订单管理");
        mIvRight2.setVisibility(View.VISIBLE);

        ButterKnife.bind(this);
        initViewPager();

        initRecyclerview();
        initListener();
        getServiceOrderList(status);

        mIvRight2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isDelete){
                    checked=1;
                    isDelete=false;
                    mIvRight2.setVisibility(View.GONE);
                    mTvRight.setVisibility(View.VISIBLE);
                    mTvRight.setTextColor(getResources().getColor(R.color.main_color));
                    mTvRight.setText("取消");
                    tv_delete.setVisibility(View.VISIBLE);
                    if (!mList.isEmpty() || mList.size() == 0) {
                        for (int i = 0; i < mList.size(); i++) {
                            mList.get(i).setGone(true);
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isDelete=true;
                checked=0;
                mTvRight.setVisibility(View.GONE);
                mIvRight2.setVisibility(View.VISIBLE);
                tv_delete.setVisibility(View.GONE);
                if (!mList.isEmpty() || mList.size() == 0) {
                    for (int i = 0; i < mList.size(); i++) {
                        mList.get(i).setGone(false);
                        mList.get(i).setChecked(false);
                    }

                    adapter.notifyDataSetChanged();
                }
            }
        });


        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                page = 1;
                isClear = true;
                status = tab.getPosition();
                LogUtils.e("111111111111",status+"");
                getServiceOrderList(status);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mIdList.size()<1){
                    RxToast.info("请选择要删除的订单");
                }else {
                    okGoDeleteOrder();
                }
            }
        });

    }

    private void initRecyclerview() {
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerview.addItemDecoration(new SimplePadding20Decoration(this));
        adapter = new BOrderListAdapter(R.layout.item_small_b_order, mList);
        recyclerview.setAdapter(adapter);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_type:
                        if (mList.get(position).getOrderStatus() == 2) {
                            Receipt(mList.get(position).getId()+"");//接单
                            //recomputeTlOffset1(5);
                        } else if (mList.get(position).getOrderStatus() == 3){
                            serviceDialog(mList.get(position).getRejectReason());
                        }
                        break;
                    case R.id.tv_refuse://拒单
                        myDialog(mList.get(position).getOnum());
                        break;
                    case R.id.ll_content:
                        mList.get(position).setChecked(!mList.get(position).isChecked());
                        adapter.notifyDataSetChanged();
                        summary();
                        break;
                }
            }
        });
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                isClear = true;
                getServiceOrderList(status);
                refreshlayout.finishRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                isClear = false;
                getServiceOrderList(status);
                refreshLayout.finishLoadMore();
            }

        });
    }

    /**
     * 重新计算需要滚动的距离
     * *
     * * @param index 选择的tab的下标
     */
    private void recomputeTlOffset1(int index) {
        if (mTabLayout.getTabAt(index) != null)
            mTabLayout.getTabAt(index).select();
        final int width = (int) (getTablayoutOffsetWidth(index) * getResources().getDisplayMetrics().density);
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                mTabLayout.smoothScrollTo(width, 0);
            }
        });
    }

    /**
     * 根据字符个数计算偏移量
     * * @param index 选中tab的下标
     *
     * @return 需要移动的长度
     */
    private int getTablayoutOffsetWidth(int index) {
        String str = "";
        for (int i = 0; i < index; i++) {
            //channelNameList是一个List<String>的对象，里面转载的是30个词条            //取出直到index的tab的文字，计算长度
            str += titles.get(i);
        }
        return str.length() * 14 + index * 12;
    }


    //获取服务订单
    private void getServiceOrderList(int status) {
        OkGo.<String>post(Config.s + "llc/carServiceOrderController/queryOrderForB")
                .tag(this)
                .params("token", UserBean.getbToken(this))
                .params("status", status)
                .params("page", page)
                .params("num", 4)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        OrderListBean orderListBean = gson.fromJson(response.body(), OrderListBean.class);
                        if (orderListBean.isIsSuccess()) {
                            if (isClear) {
                                mList.clear();
                            }
                            if (checked==1){
                                for (int i = 0; i <orderListBean.getData().getOrder().size() ; i++) {
                                    orderListBean.getData().getOrder().get(i).setGone(true);
                                }
                            }
                            mList.addAll(orderListBean.getData().getOrder());
                            adapter.setNewData(mList);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    //接单
    private void Receipt( String id) {
        OkGo.<String>post(Config.s + "llc/carServiceOrderController/receiveOrder")
                .tag(this)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            RxToast.success(baseBean.getOutputMessage());
//                            getServiceOrderList(status);
                            recomputeTlOffset1(4);

                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    private void initViewPager() {
        //        // 创建一个集合,装填Fragment
        //        List<Fragment> fragments = new ArrayList<>();
        //        // 装填
        //       fragments.add(BOrderFragment.newInstance(0,where));
        //        fragments.add(BOrderFragment.newInstance(1,where));
        //        fragments.add(BOrderFragment.newInstance(2,where));
        //        fragments.add(BOrderFragment.newInstance(3,where));

        titles = new ArrayList<>();
        titles.add("全部");
        titles.add("待支付");
        titles.add("待接单");
        titles.add("拒接单");
        titles.add("待完成");
        titles.add("已完成");
        titles.add("已评价");
        // 创建ViewPager适配器
        //        OrderPagerAdapter myPagerAdapter = new OrderPagerAdapter(getSupportFragmentManager(), fragments, titles);

        // 给ViewPager设置适配器
        //        viewPager.setAdapter(myPagerAdapter);
        // TabLayout 指示器 (记得自己手动创建4个Fragment,注意是 app包下的Fragment 还是 V4包下的 Fragment)
        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(0)), true);
        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(1)));
        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(2)));
        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(3)));
        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(4)));
        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(5)));
        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(6)));
        // 使用 TabLayout 和 ViewPager 相关联
        //        mTabLayout.setupWithViewPager(viewPager);
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(mTabLayout, 15, 15);
            }
        });
    }


    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    private void myDialog(final String pos) {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_refuse_reason, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - 200;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        TextView submit = bottomDialog.findViewById(R.id.submit);
        TextView cancel = bottomDialog.findViewById(R.id.cancel);
        final EditText editText=bottomDialog.findViewById(R.id.content);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 判断软键盘是否显示
                LogUtils.e("adadada",isSoftShowing()+"");
                if (isSoftShowing()){
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    bottomDialog.dismiss();
                }else {
                    bottomDialog.dismiss();
                }
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 隐藏软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                if (!TextUtils.isEmpty(editText.getText().toString().trim())){
                    OkGo.<String>post(Config.s + "llc/carServiceOrderController/rejectCarServiceOrder")
                            .tag(this)
                            .params("token", UserBean.getbToken(mContext))
                            .params("onum", pos)
                            .params("rejectReason", editText.getText().toString().trim())
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    Gson gson = new Gson();
                                    BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                                    if (bean.isIsSuccess()) {
                                        bottomDialog.dismiss();
                                        recomputeTlOffset1(3);
                                        RxToast.success(bean.getOutputMessage());
                                    } else {
                                        RxToast.error(bean.getOutputMessage());
                                    }

                                }
                            });
                }else {
                    RxToast.error("请填写拒单原因");
                }
            }
        });
    }

    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
         int screenHeight = getWindow().getDecorView().getHeight();
         //获取View可见区域的bottom
        Rect rect = new Rect();
        //DecorView即为activity的顶级view
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //考虑到虚拟导航栏的情况（虚拟导航栏情况下：screenHeight = rect.bottom + 虚拟导航栏高度）
        // 选取screenHeight*2/3进行判断
        return screenHeight*2/3 > rect.bottom;
    }


    private boolean isFindAllCheck() {
        for (int i = 0; i < mList.size(); i++) {
            if (!mList.get(i).isChecked()) {
                return false;
            }
        }
        return true;
    }

    public void summary() {
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).isChecked()) {
                    mIdList.add(mList.get(i).getId()+"");
                } else {
                    if (mIdList.contains(mList.get(i).getId())) {
                        mIdList.remove(mList.get(i).getId());
                    }
                }
            }
    }

    //批量删除
    private void okGoDeleteOrder() {
        OkGo.<String>post(Config.s + "llc/carServiceOrderController/deleteCarServiceOrder")
                .tag(this)
                .params("token", UserBean.getbToken(this))
                .addUrlParams("ids", mIdList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            RxToast.success(bean.getOutputMessage());
                            finish();
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    private void serviceDialog(String str) {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.refuse_reason, null);
        bottomDialog.setContentView(contentView);
        TextView tv_yuanyin = contentView.findViewById(R.id.tv_yuanyin);
        tv_yuanyin.setText(str);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - 320;
        params.bottomMargin = 40;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();
    }
}
